package com.xysd.express.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xysd.express.app.App;
import com.xysd.express.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

	private static final String TAG = "WXPayEntryActivity";

	private IWXAPI api;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(this, App.getInstance().wexinAppId);
		api.handleIntent(getIntent(), this);
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {//支付
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			builder.setTitle("支付结果");
//			builder.setMessage(String.valueOf(resp.errCode));
//			builder.show();
			int code = resp.errCode;
			Log.i("微信支付返回码errCode：",""+code);
			if (code == 0) {//支付成功
				ToastUtil.show("支付成功");
				finish();
			}
			if (code == -1) {//错误
				ToastUtil.show("支付失败:" + resp.errStr);
				finish();
			}
			if (code == -2) {//用户取消
				ToastUtil.show("支付取消:" + resp.errStr);
				finish();
			}

		}

		else if (resp.getType()==ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){
			// 分享

			String result = "";
			switch (resp.errCode) {
				case BaseResp.ErrCode.ERR_OK:
					result = "分享成功";
					break;
				case BaseResp.ErrCode.ERR_USER_CANCEL:
					result = "取消分享";
					break;
				case BaseResp.ErrCode.ERR_SENT_FAILED:
					result = "分享失败";
					break;
				default:
					result = "未知原因";
					break;
			}
			ToastUtil.show(result);
			finish();

		}else if(resp.getType()==ConstantsAPI.COMMAND_SENDAUTH){
			// 登录

			String result = "";
			switch (resp.errCode) {
				case BaseResp.ErrCode.ERR_OK:
					// 授权成功

					result = "授权成功";

					// 发送事件通知登陆界面
					EventBus.getDefault().post(resp);
					break;
				case BaseResp.ErrCode.ERR_USER_CANCEL:
					// 授权取消
					result = "取消授权";
					break;
				case BaseResp.ErrCode.ERR_AUTH_DENIED:
					// 授权被拒绝
					result = "授权被拒绝";
					break;
				default:
					// 未知错误
					result = "未知原因";
					break;
			}
			ToastUtil.show(result);
			finish();
		}
	}

}